package com.tangmimi.friends.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tangmimi.friends.model.domain.User;
import com.tangmimi.friends.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 缓存预热
 */
@Component
@Slf4j
public class PreCacheJob {
    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private RedissonClient redissonClient;


    //重点用户
    private List<Long> mainList = Arrays.asList(1L);

    //每天执行任务
    @Scheduled(cron = "0 38 13 ? * *")
    public void doCacheRecommendUser() {
        RLock lock = redissonClient.getLock("yupao:precache:job:lock");
        boolean tryLock = false;
        try {
            //过期时间设置-1 自动开启看门狗机制 可以自动续期

            tryLock = lock.tryLock(0, -1, TimeUnit.MILLISECONDS);
            if (tryLock) {
                System.out.println("getLock:" + Thread.currentThread().getId());
                for (Long userId : mainList) {
                    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                    Page<User> userPage = userService.page(new Page<User>(1, 20), queryWrapper);
                    List<User> safetyUserList = userPage.getRecords().stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
                    Page<User> safetyUserPage = userPage.setRecords(safetyUserList);
                    String redisKey = String.format("yupao:user:recommend:%s", userId);
                    //写缓存
                    try {
                        redisTemplate.opsForValue().set(redisKey, safetyUserPage, 60000, TimeUnit.MILLISECONDS);
                    } catch (Exception e) {
                        log.error("redis set key error!!!", e);
                    }
                }

            }
        } catch (InterruptedException e) {
            log.error("doCacheRecommendUser error!!!",e);
        }finally {
            //只能释放自己的锁
            if (lock.isHeldByCurrentThread()) {
                System.out.println("unLock:"+ Thread.currentThread().getId());
                lock.unlock();
            }
        }

    }
}
